/**
 * Created by xiaowuzai on 2018/5/6.
 */
import React, {Component} from 'react';
import PropTypes from "prop-types";
import { StyleSheet, TextInput, View, TouchableOpacity,Image, Platform ,Dimensions} from 'react-native';

import color from '../../config/theme/standard/color.js';
import fontSize from '../../config/theme/standard/fonts.js';
import Label from '../label/index';


export default class VerifyCode extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: this.props.time, //开始时间
            isFinish: true,
            isFirst: true, //是否是第一次渲染
            defaultValue: '',
            isRefresh: false,
            activeColor: this.props.activeColor, //按下态
        };
    }

    onTimer = () => {
        let detalTime=Math.round((Date.parse(new Date())-this.startTime)/1000);
        if(detalTime>=this.props.time){
            this.timer&&clearInterval(this.timer);
            this.setState({isFinish: true,count:0});
            //倒计时结束时的回调函数
            if(this.props.finishedFun){
                this.props.finishedFun()
            }
        }else{
            let newCountTime=this.props.time-detalTime;
            this.setState({count:newCountTime});
        }
    };

    imgClickEvent=()=>{
        this.setState({isRefresh: !this.state.isRefresh});
    };

    componentWillUnmount(){
        if(this.timer){
            clearInterval(this.timer);
        }
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.isClearInterval) {
            return {
                count: 0,
                isFinish: true
            };
        }
        return null;
    }

    componentDidUpdate(){
        if ( this.props.isClearInterval ) {
            this.timer&&clearInterval(this.timer);
        }
    }

    againTime = () => {
        this.startTime=Date.parse(new Date());
        if(this.props.returnVal){
            //倒计时开始时的回调，
            if(this.props.startedFun && this.props.startedFun()){
                if (this.state.isFinish) {
                    this.setState({
                        count: this.props.time,
                        isFinish: false,
                        isFirst: false
                    });
                    this.timer = setInterval(this.onTimer, 1000)
                }
            }

        }else{
            if (this.state.isFinish) {
                this.setState({
                    count: this.props.time,
                    isFinish: false,
                    isFirst: false
                });
                this.timer = setInterval(this.onTimer, 1000)
                //倒计时开始时的回调，
                if (this.props.startedFun) {
                    this.props.startedFun();
                }

            }
        }
    };

    getValue(){
        return this.state.defaultValue
    }

    clearInputVal(){
        this.setState({defaultValue:''})
    }

    onPressIn() {
        //this.setState({ activeColor: color.button.press});
    }

    onPressOut() {
        //this.setState({ activeColor: color.main});
    }

    onPress() {
        if (typeof this.props.onPress == 'function') {
            this.props.onPress()
        }
    }

    _onBlur=()=>{
        let defaultValue=this.state.defaultValue
        if (typeof this.props.onBlur == 'function') {
            this.props.onBlur(defaultValue)
        }
    }
    _onChange=(text)=>{
        let {type,textChangeEvent}=this.props;
        if(type=='msg'){
            let newVal=text;
            let preInputVal=this.state.defaultValue;
            let reg=new RegExp("^[0-9]*$");
            if(newVal){
                if(!reg.test(newVal)){
                    newVal=preInputVal
                };
            }else{
                newVal=''
            };
            this.setState({defaultValue:newVal})
            textChangeEvent(newVal)
        }else if(this.props.type=='img'){
            this.setState({defaultValue:text})
            if (typeof this.props.textChangeEvent == 'function') {
                this.props.textChangeEvent(text)
            }
        }
        
    }

    render(){
        let {type,normalBtnText,normalBtnSubText,tipsString,confirmText,fontStyle,keyboardType,disabled,
            btnWidth,btnAgainWidth,textStyle,btnWrapperStyle,titleWidth,textChangeEvent,isRequired}=this.props;
        let rightContent ;
        let rightComponent = this.props.rightComponent ? this.props.rightComponent : null;
        let textLeftStyles = [styles.textLeft];
        let maxTitleWidth = 125; //输入框左侧标题的最大宽度
        if (titleWidth && titleWidth <= maxTitleWidth && titleWidth>0){
          textLeftStyles.push({width:titleWidth});
        }
        if (type == 'msg'){
            if(this.state.isFirst){
                rightContent = (
                    <TouchableOpacity
                        disabled={disabled}
                        activeOpacity={1}
                        style={[styles.text, styles.textMsg, {borderColor: disabled?color.verifyCode.buttonDisableBorder:this.state.activeColor,width:btnWidth,backgroundColor: disabled ? color.verifyCode.buttonDisableBackground : color.verifyCode.buttonActiveBackground}]}
                        onPress={this.againTime}
                    >
                        <Label
                            type={'button'}
                            textAlign={"center"}
                            labelStyle={{color: disabled?color.verifyCode.buttonDisableText:this.state.activeColor}}
                            text={normalBtnText}
                        />
                    </TouchableOpacity>
                )
            } else {
                rightContent = this.state.count != 0 ?
                    <TouchableOpacity
                        disabled={true}
                        activeOpacity={0.7}
                        style={[styles.text, styles.disabled]}
                        onPress={this.againTime}
                    >
                        <Label text={this.state.count >= 10 ? this.state.count + '秒' : '0' + this.state.count + '秒'} labelStyle={{color: color.verifyCode.buttonDisableText, fontSize: fontSize.verifyCode.buttonFontSize}}/>
                    </TouchableOpacity> :
                    <TouchableOpacity
                        disabled={disabled}
                        activeOpacity={1}
                        style={[styles.text, styles.textNew, {borderColor: disabled?color.verifyCode.buttonDisableBorder:this.state.activeColor,width:btnAgainWidth,backgroundColor: disabled ? color.verifyCode.buttonDisableBackground : color.verifyCode.buttonActiveBackground,}]}
                        onPress={this.againTime}
                    >
                        <Label  textAlign={'center'} labelStyle={{color: disabled?color.verifyCode.buttonDisableText:this.state.activeColor}} text={normalBtnSubText}/>
                    </TouchableOpacity>
            }

        } else if(type == 'img'){
            rightContent = (
                <TouchableOpacity disabled={disabled}  activeOpacity={1} onPress={this.imgClickEvent}>
                    {rightComponent}
                </TouchableOpacity>
            )
        }

        let description;

      
        description = (
            <View style={[styles.descContainer, {backgroundColor: this.props.bgColor}]}>
                <Label text={tipsString}  labelStyle={{color:color.verifyCode.tip,fontSize:fontSize.verifyCode.tipFontSize}} lineHeight={22}/>
            </View>
        )
        

        let button;

        if (this.props.button) {
            button=(
                <View style={[styles.button,btnWrapperStyle?btnWrapperStyle:""]}>
                    <TouchableOpacity
                        disabled={this.state.defaultValue.length == 6 ? false : true}
                        activeOpacity={1}
                        style={[styles.primary,{backgroundColor: this.state.defaultValue.length < 6?color.button.disableBackground:this.state.activeColor}]}
                        onPress={() => this.onPress()}
                    >
                        <Label textAlign={"center"} text={confirmText} labelStyle={{color:this.state.defaultValue.length < 6?color.button.disableText:color.white,fontSize:fontSize.button.btnFontSize1}}/>
                    </TouchableOpacity>
                </View>
            )
        }
        let textInputCom=null;
        let textInputKeyBoardType='text';
        if(Platform.OS != 'web'){
            textInputCom=(
                <TextInput
                    ref={(e) => this.textInput = e}
                    style = {[styles.textInput,fontStyle]}
                    underlineColorAndroid = 'transparent'
                    placeholder = {this.props.placeHolder}
                    placeholderTextColor = {color.verifyCode.placeholder}
                    value ={this.state.defaultValue}
                    maxLength={this.props.maxLength}
                    onChangeText ={(text)=>{this._onChange(text)}}
                    onBlur={()=>{this._onBlur()}}
                    keyboardType={keyboardType}
                />
            )
        }else if(Platform.OS =='web' && type=='msg') {
            let agent= navigator.userAgent.toLowerCase();
            if(agent.indexOf('android')>-1 && agent.indexOf('webkit') > -1){
                textInputKeyBoardType='tel'
            };
            textInputCom=(
                <TextInput
                    ref={(e) => this.textInput = e}
                    style = {[styles.textInput,fontStyle]}
                    underlineColorAndroid = 'transparent'
                    placeholder = {this.props.placeHolder}
                    placeholderTextColor = {color.verifyCode.placeholder}
                    value ={this.state.defaultValue}
                    maxLength={this.props.maxLength}
                    pattern="[0-9]*"
                    onChangeText ={(defaultValue)=>{
                        let newVal=defaultValue;
                        let preInputVal=this.state.defaultValue;
                        let reg=new RegExp("^[0-9]*$");
                        newVal=newVal.slice(0,this.props.maxLength);
                        if(newVal){
                            if(!reg.test(newVal)){
                                newVal=preInputVal
                            };
                        }else{
                            newVal=''
                        };
                        this.setState({defaultValue:newVal})
                        textChangeEvent(newVal)
                    }}
                    onBlur={()=>{this._onBlur()}}
                    keyboardType={textInputKeyBoardType}
                />
            );
        }

        const starIconElement = isRequired ? 
            <Image
                source={require('../../assets/verifyCode_star.png')}
                style={styles.starIcon} 
            /> : null;

        return(
            <View>
                <View style={[styles.container, {borderTopWidth: this.props.hasTopBorder ?  1 : 0}]}>
                    <View style={textLeftStyles}>
                        <Label text={this.props.tip} labelStyle={[{color:color.verifyCode.title,fontSize:fontSize.verifyCode.titleFontSize},textStyle]}/>
                        {starIconElement}
                    </View>
                    <View style={styles.textCenter}>
                       {textInputCom}
                    </View>
                    <View style={styles.textRight}>
                        {rightContent}
                    </View>
                </View>
                <View style={[styles.divider, {marginLeft: this.props.isMerge ? 15 : 0}]}/>
                {description}
                {button}
            </View>
        )

    }
};

VerifyCode.propTypes = {
    //默认文本最多可输入的个数
    maxLength: PropTypes.number,
    //计时时间
    time: PropTypes.number,
    //文字标签
    tip: PropTypes.string,
    //类型（短信/图形）
    type: PropTypes.oneOf(['msg', 'img']),
    //提示文字
    placeHolder: PropTypes.string,
    //获取倒计时的回调函数
    startedFun: PropTypes.func,
    //倒计时结束时的回调函数
    finishedFun: PropTypes.func,
    //是否有上边框
    hadTopBorder: PropTypes.bool,
    //是否合并样式
    isMerge: PropTypes.bool,
    //手机号
    //phoneNumber: PropTypes.string,
    //验证码编号
    //codeNumber: PropTypes.string,
    //提示语底色
    bgColor: PropTypes.string,
    //是否有按钮
    button: PropTypes.bool,
    //按钮的点击事件
    onPress: PropTypes.func,
    //按钮默认提示语
    normalBtnText:PropTypes.string,
    //按钮重新获取验证码的提示语
    normalBtnSubText:PropTypes.string,
    //是否为必输项，显示小红星
    isRequired: PropTypes.bool,

    //提示
    tipsString:PropTypes.string,
    //确定按钮文本
    confirmText:PropTypes.string,
    //输入框的样式
    fontStyle:PropTypes.object,
    //是否清空倒计时
    isClearInterval:PropTypes.bool,
    //弹起键盘类型
    keyboardType: PropTypes.oneOf(['default','numeric','email-address','phone-pad']),
    //按钮是否可点击
    disabled:PropTypes.bool,
    //点击时的回调是否有返回值
    returnVal:PropTypes.bool,
    //获取按钮的宽度
    btnWidth:PropTypes.number,
    //重新获取按钮的宽度
    btnAgainWidth:PropTypes.number,
    //左边文字样式
    textStyle:PropTypes.object,
    //按钮选中状态的颜色
    activeColor:PropTypes.string,
    //
    btnWrapperStyle:PropTypes.object,
    //输入框左侧标题宽度
    titleWidth:PropTypes.number,
    //输入框onTextChange事件回调函数
    textChangeEvent:PropTypes.func
    };

VerifyCode.defaultProps = {
    //计时时间
    time: 60,
    //文字标签
    tip: '短信验证码',
    //类型（短信）
    type: 'msg',
    //提示文字
    placeHolder: '请输入6位数字',
    //是否有上边框
    hasTopBorder: true,
    //是否合并样式
    isMerge: false,
    //提示语底色
    bgColor: '#F5F7F9', 
    //是否有按钮
    button: false,
    //默认文本最多可输入的个数
    maxLength:6,
    //按钮默认提示语
    normalBtnText:"获取",
    //按钮重新获取验证码的提示语
    normalBtnSubText:"重新获取",
    //tips
    tipsString:"已发送，请注意查收，如未收到请核实预留手机号，再进行后续操作",
    //确定按钮文本
    confirmText:"确定",
    //是否清空倒计时
    isClearInterval:false,
    //弹起键盘类型
    keyboardType:"numeric",
    //按钮是否可点击
    disabled:false,
    //按钮点击时的回调函数的返回值
    returnVal:false,
    //获取按钮的宽度
    btnWidth:42,
    //重新获取按钮的宽度
    btnAgainWidth:70,
    //
    activeColor: color.verifyCode.buttonActive, //按下态
    //
    btnWrapperStyle:{backgroundColor:'white'},
    isRequired: false,
    textChangeEvent:()=>{}
};

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingLeft: 15,
        paddingRight: 15,
        borderTopColor: color.border,
        minHeight: 44,
        backgroundColor: color.white
    },
    textLeft: {
        width:112,
        alignItems: 'center',
        flexDirection: 'row'
    },
    starIcon:{
        height:8,
        width:8,
        resizeMode:'contain',
        marginLeft:5
    },
    textCenter: {
        flex: 1,
        height: 44,
        justifyContent: 'center',
        marginRight: 8
    },
    textRight: {
        height: 36,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end'
    },
    textInput: {
        fontSize: fontSize.verifyCode.inputFontSize,
        borderWidth: 0,
        margin: 0,
        padding: 0,
        color: color.verifyCode.input
    },
    text: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: color.white,
        height: 26,
        borderWidth: 1,
        borderRadius: 2
    },
    textMsg: {
        width: 42
    },
    textNew: {
        width: 70
    },
    disabled: {
        width: 42,
        backgroundColor:color.verifyCode.buttonDisableBackground,
        borderColor: color.verifyCode.buttonDisableBorder,
    },
    divider: {
        height: 1,
        backgroundColor: color.border
    },
    descContainer: {
        flexDirection: 'row',
        paddingVertical: 5,
        paddingHorizontal: 15
    },
    button: {
        justifyContent: 'center',
        alignItems: 'center',
        paddingTop: 20
    },
    primary: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: color.button.active,
        borderRadius: 2,
        width: Dimensions.get('window').width-30,
        height: 44,
        paddingHorizontal: 10,
    },
});
